package com.cssw.fyzb.core.eao.user;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.core.eao.video.VideoLikeEao;
import com.cssw.fyzb.core.es.EsClient;
import com.cssw.fyzb.core.model.eos.UserEo;
import com.cssw.fyzb.core.model.eos.VideoLikeEo;
import com.cssw.fyzb.core.util.DateUtil;
import com.ydn.dbframe.plugin.activerecord.Page;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author YangYiQun
 */
@Component
public class UserEaoImpl implements UserEao {

    @Autowired
    private EsClient esClient;

    private final static String INDEX_NAME = "fyzb_user";
    private final static String TYPE_NAME = "fyzb_user";

    @Override
    public long delete(Long userId) {
        VideoLikeEo videoLikeEo = new VideoLikeEo();
        videoLikeEo.setUserId(userId);

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.filter().add(QueryBuilders.termQuery("userId", userId));

        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(esClient.getClient())
                        .filter(queryBuilder)
                        .source(INDEX_NAME)
                        .get();

        return response.getDeleted();
    }

    @Override
    public void save(Long userId, Long fyNo, String nickName, String mobile, Date createTime) {
        UserEo userEo = new UserEo();
        userEo.setUserId(userId);
        userEo.setNickName(nickName);
        userEo.setMobile(mobile);
        userEo.setFyNo(fyNo);
        userEo.setCreateTime(DateUtil.format(createTime));

        esClient.getClient()
                .prepareIndex(INDEX_NAME, TYPE_NAME)
                .setId(userId.toString())
                .setSource(JSON.parseObject(JSON.toJSONString(userEo)))
                .get()
        ;

    }
}
